package org.je.log;

import java.util.Date;

import org.je.util.DateUtil;
import org.je.util.DynBuffer;

/**
 * @author fanyifeng 2012-8-31 下午12:35:52
 */
public class JLog
{
	private static final LogBuffer	info	= new LogBuffer(LogPath.get() + "/info.log");
	private static final LogBuffer	error	= new LogBuffer(LogPath.get() + "/error.log");
	private static volatile String	logTime	= getTime();

	static {
		new LogThread(info, error).start();
	}

	public static void showPath() {
		System.out.println("logPath: " + LogPath.get());
	}

	public static void out(Object o) {
		if (o == null) {
			System.out.println("null");
		} else if (o.getClass() == byte[].class) {
			System.out.println(new String((byte[]) o));
		} else {
			System.out.println(o);
		}
	}

	public static void info(Object o) {
		try {
			info.save(getBytes(o));
		} catch (Throwable ex) {
			ex.printStackTrace();
		}
	}

	public static void error(Object o) {
		try {
			error.save(getBytes(o));
		} catch (Throwable ex) {
			ex.printStackTrace();
		}
	}

	private static byte[] getBytes(Object o) {
		DynBuffer bf = new DynBuffer();
		bf.append(logTime.getBytes());
		if (o != null) {
			if (o instanceof Throwable) {
				bf.append(ErrorUtil.toBytes((Throwable) o));
			} else {
				bf.append(o.toString().getBytes());
			}
		}
		bf.append("\r\n".getBytes());
		return bf.toArray();
	}

	private static String getTime() {
		try {
			return DateUtil.fromat(new Date()) + "  ";
		} catch (Throwable ex) {}
		return "";
	}

	static void updateTime() {
		logTime = getTime();
	}

}
